using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Random = UnityEngine.Random;

public class SpawnManager : MonoBehaviour
{
    [SerializeField] private GameObject shieldPowerup;
    private float spawnRangeX = 9;
    private float spawnRangeY = 4;

    [SerializeField] private GameObject asteroidPrefab;
    [SerializeField] private GameObject lifePowerup;

    private int waveNumber = 1;

    private int asteroidCount;
    private int littleAsteroidCount;

    [SerializeField] private GameManager gameManager;

    private void Start()
    {
        InvokeRepeating("SpawnShieldPowerup", 1f, 5f);
        InvokeRepeating("SpawnLifePowerup", 1f, 10f);

        SpawnAsteroids(waveNumber);
    }

    private void Update()
    {
        if (gameManager.isGameActive == true && !gameManager.isPaused)
        {
            asteroidCount = FindObjectsOfType<AsteroidController>().Length;
            littleAsteroidCount = FindObjectsOfType<LittleAsteroidController>().Length;

            if (asteroidCount == 0 && littleAsteroidCount == 0)
            {
                waveNumber++;
                SpawnAsteroids(waveNumber);
            }
        }
    }

    private void SpawnShieldPowerup()
    {
        if (gameManager.isGameActive)
        {
            Instantiate(shieldPowerup, GeneratePosition(), shieldPowerup.transform.rotation);
        }
    }
    
    private void SpawnLifePowerup()
    {
        if (gameManager.isGameActive)
        {
            Instantiate(lifePowerup, GeneratePosition(), lifePowerup.transform.rotation);
        }
    }

    private Vector3 GeneratePosition()
    {
        float spawnPosX = Random.Range(-spawnRangeX, spawnRangeX);
        float spawnPosY = Random.Range(-spawnRangeY, spawnRangeY);
        Vector3 randomPos = new Vector3(spawnPosX, spawnPosY, 0);

        Collider[] hitColliders = Physics.OverlapSphere(randomPos, 3.0f);
        if (hitColliders != null)
        {
            foreach (Collider hit in hitColliders)
            {
                if (hit.CompareTag("Player"))
                {
                    // 递归判断是否找到合适的postion
                    GeneratePosition();
                }
            }
        }

        return randomPos;
    }

    private void SpawnAsteroids(int asteroidsToSpawn)
    {
        for (int i = 0; i < asteroidsToSpawn; i++)
        {
            Instantiate(asteroidPrefab, GeneratePosition(), asteroidPrefab.transform.rotation);
        }
    }
}